<script setup>
	import { ref, computed } from "vue"
	import { gotoHome } from "@/utils/common.js"
	import { onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app"
	import { setupScoreAPI, setDownloadAPI, getDetailAPI } from "@/api/preview.js"
	import { getStatusBarHeight, getMenuButtonTop, getTitleBarHeight } from "@/utils/system.js"

	// 图片列表
	const classifyList = ref([])
	const storageClassifyList = uni.getStorageSync("classifyList") || []
	classifyList.value = storageClassifyList.map(item => {
		return {
			...item,
			picurl: item.smallPicurl.replace("_small.webp", ".jpg")
		}
	})
	// 当前图片
	const currentId = ref(0)
	const currentIndex = ref(-1)
	const currentImg = computed(() => {
		return currentIndex.value === -1 ? {} : classifyList.value[currentIndex.value]
	})
	// 轮播图切换
	const onSwiperChange = (e) => {
		currentIndex.value = e.detail.current
		setReadImg()
	}

	// 缓存看过的图片
	const readImgList = ref([])
	const setReadImg = () => {
		// 上一张
		const pre = currentIndex.value === 0 ? classifyList.value.length - 1 : currentIndex.value - 1
		// 下一张
		const next = currentIndex.value === classifyList.value.length - 1 ? 0 : currentIndex.value + 1
		readImgList.value.push(pre, currentIndex.value, next)
		readImgList.value = [...new Set(readImgList.value)]
	}

	// 胶囊的高度
	const menuButtonH = computed(() => {
		return getTitleBarHeight() - (getMenuButtonTop() * 2)
	})
	// 返回上一页
	const onBack = () => {
		uni.navigateBack({
			fail() {
				uni.reLaunch({ url: "/pages/index/index" })
			}
		})
	}

	// 显示/隐藏图片详情
	const isShowMask = ref(true)
	const onToggleMask = () => {
		isShowMask.value = !isShowMask.value
	}

	// 壁纸信息弹窗
	const infoPopupRef = ref(null)
	const onOpenInfo = () => infoPopupRef.value.open()
	const onCloseInfo = () => infoPopupRef.value.close()

	// 评分弹窗
	const scorePopupRef = ref(null)
	const onOpenScore = () => {
		isScore.value = false
		userScore.value = 0

		if (currentImg.value.userScore) {
			isScore.value = true
			userScore.value = currentImg.value.userScore
		}
		scorePopupRef.value.open()
	}
	const onCloseScore = () => scorePopupRef.value.close()
	// 用户评分
	const isScore = ref(false) // 是否评分过
	const userScore = ref(0)
	const scoreLoading = ref(false)
	const onSubmitScore = async () => {
		const { classid, _id: wallId } = currentImg.value
		try {
			scoreLoading.value = true
			await setupScoreAPI({ classid, wallId, userScore: userScore.value })
			uni.showToast({ title: '评分成功', icon: "none" })
			onCloseScore()
			// 添加到缓存
			classifyList.value[currentIndex.value].userScore = userScore.value
			uni.setStorageSync("classifyList", classifyList.value)
		} finally {
			scoreLoading.value = false
		}
	}

	// 图片下载
	const onDownload = async () => {
		// #ifdef H5
		uni.showModal({ content: "请长按保存壁纸", showCancel: false })
		// #endif

		// #ifndef H5
		uni.showLoading({ title: "下载中...", mask: true })
		try {
			// 设置下载记录
			const { classid, _id: wallId } = currentImg.value
			await setDownloadAPI({ classid, wallId })
			// 获取图片详情
			uni.getImageInfo({
				src: currentImg.value.picurl,
				success(res) {
					// 保存图片
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success(res) {
							uni.showToast({ title: "保存成功", icon: "none" })
						},
						fail(err) {
							console.log(err);
							// 取消保存
							if (err.errMsg === "saveImageToPhotosAlbum:fail cancel") {
								uni.showToast({ title: "保存失败，请点击重新下载", icon: "none" })
								return
							}
							// 授权
							uni.showModal({
								title: "授权提示",
								content: "需要授权保存相册",
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(setting) {
												if (setting.authSetting["scope.writePhotosAlbum"]) {
													uni.showToast({ title: "获取授权成功", icon: "none" })
												} else {
													uni.showToast({ title: "获取授权失败", icon: "none" })
												}
											}
										})
									}
								}
							})
						},
						complete() {
							uni.hideLoading()
						}
					})
				}
			})

		} catch (e) {
			uni.hideLoading()
		}
		// #endif
	}
	// 页面加载
	onLoad(async (options) => {
		currentId.value = options.id
		if (!options.id) return gotoHome()
		// 判断是否分享
		if (options.type === "share") {
			// 获取单张壁纸详情
			const { data } = await getDetailAPI({ id: currentId.value })
			// 处理数据
			classifyList.value = data.map((item) => {
				return {
					...item,
					picurl: item.smallPicurl.replace("_small.webp", ".jpg")
				}
			})
		}
		currentIndex.value = classifyList.value.findIndex(item => item._id === currentId.value)
		setReadImg()
	})

	// 分享好友
	onShareAppMessage((e) => {
		return {
			title: `拾光壁纸`,
			path: `/pages/preview/preview?id=${currentId.value}&type=share`
		}
	})
	// 分享朋友圈
	onShareTimeline(() => {
		return {
			title: `拾光壁纸`,
			query: `id=${currentId.value}&type=share`
		}
	})
</script>

<template>
	<view class="preview" v-if="currentImg">
		<!-- 轮播 -->
		<swiper class="swiper" :current="currentIndex" circular @change="onSwiperChange">
			<swiper-item v-for="(item,index) in classifyList" :key="item._id">
				<image class="image" v-if="readImgList.includes(index)" :src="item.picurl" mode="aspectFill"
					@click="onToggleMask">
				</image>
			</swiper-item>
		</swiper>
		<!-- 遮罩层 -->
		<view class="mask" v-show="isShowMask">
			<!-- #ifndef MP-WEIXIN -->
			<view class="go-back" :style="{top:(getStatusBarHeight()||15)+'px'}" @click="onBack">
				<uni-icons type="back" size="20" color="#fff"></uni-icons>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<view class="go-back"
				:style="{width:menuButtonH+'px',height:menuButtonH+'px',top:getStatusBarHeight()+getMenuButtonTop()+'px'}"
				@click="onBack">
				<uni-icons type="back" size="18" color="#fff"></uni-icons>
			</view>
			<!-- #endif -->
			<view class="count">{{currentIndex+1}} / {{classifyList.length}}</view>
			<view class="time">
				<uni-dateformat class="current-day" :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat class="current-day" :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="item" @click="onOpenInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="item" @click="onOpenScore">
					<uni-icons type="star" size="23"></uni-icons>
					<view class="text">{{currentImg.score}}分</view>
				</view>
				<view class="item" @click="onDownload">
					<uni-icons type="download" size="23"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		<!-- 壁纸信息弹窗 -->
		<uni-popup ref="infoPopupRef" type="bottom" :safe-area="false">
			<view class="info-popup">
				<view class="popup-top">
					<view class=""></view>
					<view class="title">壁纸信息</view>
					<view class="close" @click="onCloseInfo"><uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<scroll-view scroll-y>
					<view class="row">
						<text class="label">壁纸ID：</text>
						<view class="value" selectable>{{currentImg._id}}</view>
					</view>
					<!-- <view class="row">
						<text class="label">分类：</text>
						<view class="value classify" selectable>美女明星</view>
					</view> -->
					<view class="row">
						<text class="label">发布者：</text>
						<view class="value" selectable>{{currentImg.nickname}}</view>
					</view>
					<view class="row">
						<text class="label">评分：</text>
						<view class="value rate">
							<uni-rate :value="currentImg.score" size="16" readonly />
							<text class="score">{{currentImg.score}}分</text>
						</view>
					</view>
					<view class="row">
						<text class="label">摘要：</text>
						<view class="value" selectable>{{currentImg.description}}</view>
					</view>
					<view class="row">
						<text class="label">标签：</text>
						<view class="value tabs">
							<view class="tab" v-for="item in currentImg.tabs" :key="item">{{item}}</view>
						</view>
					</view>
					<view class="statement">
						声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台, 邮箱 513894357@qq.com ,管理将删除侵权壁纸，维护您的权益。
					</view>
					<view class="safe-area-inset-bottom"></view>
				</scroll-view>
			</view>
		</uni-popup>
		<!-- 评分弹窗 -->
		<uni-popup ref="scorePopupRef" :is-mask-click="false">
			<view class="score-popup">
				<view class="popup-top">
					<view class=""></view>
					<view class="title">{{isScore?'评分过了~':'壁纸评分'}}</view>
					<view class="close" @click="onCloseScore"><uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<view class="content">
					<uni-rate v-model="userScore" size="20" :readonly="isScore" allow-half />
					<text class="score">{{userScore}}分</text>
				</view>
				<view class="footer">
					<button size="mini" :loading="scoreLoading" :disabled="!userScore || isScore" plain
						@click="onSubmitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;
		color: #fff;

		.swiper {
			width: 100%;
			height: 100%;

			.image {
				width: 100%;
				height: 100%;
			}
		}

		.mask {
			&>view {
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
			}

			.go-back {
				width: 38px;
				height: 38px;
				background-color: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				transform: translateX(0);
				border-radius: 38px;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.count {
				top: 10vh;
				background-color: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;
				padding: 8rpx 28rpx;
				border-radius: 40rpx;
				backdrop-filter: blur(10rpx);
			}

			.time {
				top: calc(10vh + 80rpx);
				font-size: 140rpx;
				font-weight: 100;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.date {
				top: calc(10vh + 230rpx);
				font-size: 34rpx;
				text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
			}

			.footer {
				bottom: 10vh;
				background-color: rgba(255, 255, 255, 0.8);
				width: 65vw;
				height: 120rpx;
				border-radius: 60rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(15rpx);

				.item {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 2rpx 12rpx;
					height: 100%;

					.text {
						font-size: 26rpx;
						color: $text-color-2;
					}
				}
			}
		}
	}

	.popup-top {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title {
			color: $text-color-2;
		}

		.close {
			padding: 6rpx;
		}

	}

	.info-popup {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 30rpx 30rpx 0 0;

		scroll-view {
			max-height: 60vh;

			.row {
				display: flex;
				padding: 16rpx 0;
				font-size: 32rpx;
				line-height: 1.7em;

				.label {
					font-size: 30rpx;
					color: $text-color-3;
					text-align: right;
					width: 140rpx;
					flex-shrink: 0;
				}

				.value {
					color: $text-color-2;
					flex: 1;
				}

				.classify {
					color: $primary-color;
				}

				.rate {
					display: flex;
					align-items: center;

					.score {
						font-size: 26rpx;
						color: $text-color-2;
						margin-left: 10rpx;
					}
				}

				.tabs {
					display: flex;
					flex-wrap: wrap;

					.tab {
						border: 1px solid $primary-color;
						color: $primary-color;
						font-size: 22rpx;
						padding: 10rpx 30rpx;
						border-radius: 40rpx;
						line-height: 1em;
						margin: 0 10rpx 10rpx 0;
					}
				}
			}

			.statement {
				font-size: 28rpx;
				padding: 20rpx;
				background-color: #f6f6f6;
				color: #666;
				border-radius: 10rpx;
				margin: 20rpx 0;
				line-height: 1.6em;
			}
		}
	}

	.score-popup {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 30rpx;
		width: 70vw;

		.content {
			margin: 30rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;

			.score {
				color: #ffca3e;
				margin-left: 10rpx;
				width: 80rpx;
				line-height: 1em;
				text-align: right;
			}
		}

		.footer {
			margin: 10rpx 0;
			display: flex;
			justify-content: center;
		}
	}
</style>